package com.jianying.day08;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

/**
 * ClassName: Flink01_KeyedState_ValueState_1
 * Package: com.atguigu.day08
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/9 09:40
 * @Version: 1.0
 */
public class Flink03_KeyedState_ListState {
    public static void main(String[] args) throws Exception {
        // TODO 针对每种传感器 输出最高的3个水位值
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> mapDS = env.socketTextStream("localhost", 8888)
                .map(new WaterSensorMapFunction());

        // TODO 按键分组 ID
        KeyedStream<WaterSensor, String> keyByDS = mapDS.keyBy(WaterSensor::getId);

        // TODO 分组后数据处理
       keyByDS.process(
               new KeyedProcessFunction<String, WaterSensor, String>() {
                   // TODO 定义列表状态 存放当前设备最高的3个水位值
                   ListState<Integer> vcListState;

                   @Override
                   public void open(Configuration parameters) throws Exception {
                       ListStateDescriptor<Integer> listStateDescriptor = new ListStateDescriptor<Integer>("vcListState", Integer.class);
                       vcListState = getRuntimeContext().getListState(listStateDescriptor);
                   }

                   @Override
                   public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                       vcListState.add(value.getVc());
                       ArrayList<Integer> vcList = new ArrayList<>();
                       for (Integer vc : vcListState.get()) {
                           vcList.add(vc);
                       }
                       vcList.sort((o1,o2) -> o2 - o1);

                       if(vcList.size() > 3) {
                           vcList.remove(3);
                       }
                       out.collect("传感器:" + ctx.getCurrentKey() + "，前三水位值：" + vcList );

                       vcListState.update(vcList);
                   }
               }
       ).printToErr();

        env.execute();
    }
}
